package cn.cttic.app.service.impl;

import cn.cttic.app.api.enums.SaleOrderStatus;
import cn.cttic.base.api.domain.BaseCompany;
import cn.cttic.base.api.domain.BaseDevice;
import cn.cttic.base.api.domain.BaseProduct;
import cn.cttic.base.api.domain.BaseUser;
import cn.cttic.base.api.domain.vo.BaseDeviceVo;
import cn.cttic.base.api.domain.vo.BaseProductVo;
import cn.cttic.common.core.exception.app.AppException;
import cn.cttic.common.core.exception.link.LinkException;
import cn.cttic.link.api.RemoteThirdDistributeService;
import cn.cttic.link.api.RemoteThirdMagooService;
import cn.cttic.link.api.domain.vo.GisTimePosistionVo;
import cn.cttic.order.api.domain.BaseInstallOrder;
import cn.cttic.order.api.domain.BaseInstallOrderProcess;
import cn.cttic.order.api.domain.BaseSaleOrder;
import cn.cttic.order.api.domain.bo.BaseInstallOrderProcessBo;
import cn.cttic.order.api.domain.vo.BaseInstallOrderProcessVo;
import cn.cttic.order.api.domain.vo.BaseInstallOrderVo;
import cn.cttic.order.api.domain.vo.BaseSaleOrderVo;
import cn.cttic.resource.api.domain.RemoteFile;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.cttic.app.api.domain.bo.DoInstallActionBo;
import cn.cttic.app.api.domain.bo.InstallOrderQueryBo;
import cn.cttic.app.api.domain.vo.*;
import cn.cttic.app.api.enums.Gender;
import cn.cttic.app.api.enums.InstallOrderStatus;
import cn.cttic.app.config.BaiduAipClient;
import cn.cttic.app.mapper.*;
import cn.cttic.app.service.*;
import cn.cttic.app.utils.OrderHelper;
import cn.cttic.common.core.exception.user.UserException;
import cn.cttic.common.core.utils.BeanCopyUtils;
import cn.cttic.common.core.utils.StringUtils;
import cn.cttic.common.mybatis.core.page.TableDataInfo;
import cn.cttic.common.satoken.model.AppLoginUser;
import cn.cttic.common.satoken.utils.AppLoginHelper;
import cn.cttic.resource.api.RemoteFileService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.json.JSONObject;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
@RefreshScope
public class AppInstallServiceImpl implements IAppInstallService {

    private final BaseSaleOrderMapper baseSaleOrderMapper;
    private final IBaseSaleOrderService baseSaleOrderService;

    private final BaseInstallOrderMapper baseInstallOrderMapper;

    private final BaseCompanyMapper baseCompanyMapper;

    private final BaseUserMapper baseUserMapper;

    private final BaseProductMapper baseProductMapper;
    private final IBaseProductService baseProductService;

    private final BaseDeviceMapper baseDeviceMapper;
    private final IBaseDeviceService baseDeviceService;

    private final IAppInstallService appInstallService;

    @DubboReference
    private RemoteFileService remoteFileService;

    private final AppInstallMapper appInstallMapper;

    private final BaiduAipClient baiduAipClient;

    private final OrderHelper orderHelper;

    private final IBaseInstallOrderProcessService installOrderProcessService;

    private final BaseInstallOrderProcessMapper installOrderProcessMapper;

    @DubboReference
    private RemoteThirdMagooService remoteThirdMagooService;

    @DubboReference
    private RemoteThirdDistributeService remoteThirdDistributeService;

    private final String baseDomain = "https://setup.cttic-bd.com/i/";

    @Override
    public BaseInstallOrderProcessVo BasedoInstallAction(MultipartFile file, DoInstallActionBo installActionBo) {
        try {
            RemoteFile uploadedFile = remoteFileService.upload(file.getName(), file.getOriginalFilename(), "image", file.getBytes());

            BaseInstallOrderProcessBo installOrderProcessBo = new BaseInstallOrderProcessBo();
            installOrderProcessBo.setInstallOrderId(installActionBo.getOrderId());
            installOrderProcessBo.setOssId(uploadedFile.getOssId().toString());
            installOrderProcessBo.setOssUrl(uploadedFile.getUrl());
            installOrderProcessBo.setStepId(installActionBo.getStepId());
            installOrderProcessBo.setStepGroupName(installActionBo.getStepGroupId());
            if (installOrderProcessService.insertByBo(installOrderProcessBo)) {
                return BeanCopyUtils.copy(installOrderProcessBo, BaseInstallOrderProcessVo.class);
            } else {
                throw new AppException("未能成功提交");
            }

        } catch (Exception ex) {
            throw new AppException(ex.getMessage());
        }
    }

    /**
     * 检查设备信息
     *
     * @param imeiCode     IMEI 号码
     * @param installOrder
     * @return 检查是否成功
     */
    @Override
    public boolean checkDevice(String imeiCode, BaseInstallOrder installOrder) {
        return true;
    }

    /**
     * 绑定设备
     *
     * @param imeiCode     IMEI 号码
     * @param installOrder
     * @return 绑定是否成功
     */
    @Override
    public boolean bindDevice(String imeiCode, BaseInstallOrder installOrder) {
        return true;
    }

    /**
     * 检查并绑定设备
     *
     * @param imeiCode        IMEI 号码
     * @param installActionBo
     * @return 检查绑定是否成功
     */
    @Override
    public boolean checkAndBindDevice(String imeiCode, DoInstallActionBo installActionBo) {
        try {
            // 定义返回值
            BaseInstallOrderProcessUploadVo resultVo = null;

            // 检查是否已经有了数据
            BaseInstallOrderProcessBo process = null;
            Boolean isNew = false;

            BaseInstallOrderProcessBo query = new BaseInstallOrderProcessBo();
            query.setStepId(installActionBo.getStepId());
            query.setInstallOrderId(installActionBo.getOrderId());
            List<BaseInstallOrderProcessVo> vos = installOrderProcessService.queryList(query);

            if (CollUtil.isEmpty(vos)) {
                isNew = true;
                process = new BaseInstallOrderProcessBo();
                process.setInstallOrderId(installActionBo.getOrderId());
                process.setStepId(installActionBo.getStepId());
                process.setStepGroupName(installActionBo.getStepGroupId());
            } else {
                process = BeanCopyUtils.copy(vos.get(0), BaseInstallOrderProcessBo.class);
            }

            // 检查终端信息
            if (!remoteThirdDistributeService.queryTerminal(process.getInstallOrderId(), imeiCode)) {
                if (!remoteThirdDistributeService.registerTerminal(process.getInstallOrderId(), imeiCode)) {
                    throw new AppException("终端注册失败");
                }

                if (!remoteThirdDistributeService.queryTerminal(process.getInstallOrderId(), imeiCode)) {
                    throw new AppException("查询终端失败");
                }
            }

            process.setInteriorData(imeiCode);
            BaseInstallOrderVo baseInstallOrderVo = baseInstallOrderMapper.selectVoById(process.getInstallOrderId());
            baseInstallOrderVo.setImei(imeiCode);
            BaseInstallOrder baseInstallOrder = BeanCopyUtils.copy(baseInstallOrderVo, BaseInstallOrder.class);
            if (baseInstallOrderMapper.updateById(baseInstallOrder) <= 0) {
                throw new AppException("更新安裝單失敗");
            }

            if ((isNew && installOrderProcessService.insertByBo(process)) || (!isNew && installOrderProcessService.updateByBo(process))) {
                return true;
            } else {
                throw new AppException("未能成功提交");
            }

        } catch (Exception ex) {
            throw new AppException(ex.getMessage());
        }
    }

    /**
     * 检查并绑定设备
     *
     * @param orderId@return 检查绑定是否成功
     */
    @Override
    public boolean checkIfDeviceBinded(String orderId) {
        BaseInstallOrderProcessBo query = new BaseInstallOrderProcessBo();
        query.setStepId("10010");
        query.setInstallOrderId(orderId);
        List<BaseInstallOrderProcessVo> vos = installOrderProcessService.queryList(query);

        if (CollUtil.isEmpty(vos) || StrUtil.isEmpty(vos.get(0).getInteriorData())) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 上传行驶证主页
     *
     * @param files           行驶证副页图片列表
     * @param installActionBo 上传行驶证主页参数
     * @return
     */
    @Override
    public BaseInstallOrderProcessVo uploadVehicleLicenseMainPage(List<MultipartFile> files, DoInstallActionBo installActionBo) {
        try {
            List<RemoteFile> sysFiles = new ArrayList<>();
            for (MultipartFile file : files) {
                RemoteFile uploadedFile = remoteFileService.upload(file.getName(), file.getOriginalFilename(), "image", file.getBytes());
                sysFiles.add(uploadedFile);
            }
            BaseInstallOrderProcessBo installOrderProcessBo = new BaseInstallOrderProcessBo();
            installOrderProcessBo.setInstallOrderId(installActionBo.getOrderId());
            String ossIds = sysFiles.stream().map(x -> x.getOssId().toString()).collect(Collectors.joining(","));
            installOrderProcessBo.setOssId(ossIds);
            String ossUrls = sysFiles.stream().map(x -> x.getUrl().toString()).collect(Collectors.joining(","));
            installOrderProcessBo.setOssUrl(ossUrls);
            installOrderProcessBo.setStepId(installActionBo.getStepId());
            installOrderProcessBo.setStepGroupName(installActionBo.getStepGroupId());
            if (installOrderProcessService.insertByBo(installOrderProcessBo)) {
                return BeanCopyUtils.copy(installOrderProcessBo, BaseInstallOrderProcessVo.class);
            } else {
                throw new AppException("未能成功提交");
            }

        } catch (Exception ex) {
            throw new AppException(ex.getMessage());
        }
    }

    /**
     * 上传行驶证主页
     *
     * @param files           行驶证副页图片列表
     * @param installActionBo 上传行驶证主页参数
     * @return
     */
    @Override
    public BaseInstallOrderProcessUploadVo addVehicleLicenseMainPage(MultipartFile file, DoInstallActionBo installActionBo) {
        log.info("[上传行驶证主页][开始]");
        log.info("[上传行驶证主页][入参][{}][{}]", file.getOriginalFilename(), JSON.toJSONString(installActionBo));
        try {
            // 定义返回值
            BaseInstallOrderProcessUploadVo resultVo = null;

            // 检查是否已经有了数据
            BaseInstallOrderProcessBo process = null;
            Boolean isNew = false;

            BaseInstallOrderProcessBo query = new BaseInstallOrderProcessBo();
            query.setStepId(installActionBo.getStepId());
            query.setInstallOrderId(installActionBo.getOrderId());
            List<BaseInstallOrderProcessVo> vos = installOrderProcessService.queryList(query);

            if (CollUtil.isEmpty(vos)) {
                isNew = true;
                process = new BaseInstallOrderProcessBo();
                process.setInstallOrderId(installActionBo.getOrderId());
                process.setStepId(installActionBo.getStepId());
                process.setStepGroupName(installActionBo.getStepGroupId());
            } else {
                process = BeanCopyUtils.copy(vos.get(0), BaseInstallOrderProcessBo.class);
            }

            List<String> ossIds = (isNew || StrUtil.isEmpty(process.getOssId())) ? new ArrayList<>() : Arrays.stream(process.getOssId().split(",")).collect(Collectors.toList());
            List<String> ossUrls = (isNew || StrUtil.isEmpty(process.getOssUrl())) ? new ArrayList<>() : Arrays.stream(process.getOssUrl().split(",")).collect(Collectors.toList());

            if (ossIds.size() >= 3) {
                throw new AppException("附件已经到达最大值");
            }

            // 上传文件
            RemoteFile uploadedFile = remoteFileService.upload(file.getName(), file.getOriginalFilename(), "image", file.getBytes());

            if (!ossIds.contains(uploadedFile.getOssId())) {
                ossIds.add(uploadedFile.getOssId().toString());
            }
            if (!ossUrls.contains(uploadedFile.getUrl())) {
                ossUrls.add(uploadedFile.getUrl());
            }

            process.setOssId(ossIds.size() == 1 ? ossIds.get(0) : ossIds.stream().collect(Collectors.joining(",")));
//            process.setOssUrl(ossUrls.size() == 1 ? ossUrls.get(0) : ossUrls.stream().collect(Collectors.joining(",")));

            List<RemoteFile> ossList = remoteFileService.selectByIds(process.getOssId());
            process.setOssUrl(ossList.stream().map(x -> x.getUrl().toString()).collect(Collectors.joining(",")));

            if ((isNew && installOrderProcessService.insertByBo(process)) || (!isNew && installOrderProcessService.updateByBo(process))) {
                resultVo = BeanCopyUtils.copy(process, BaseInstallOrderProcessUploadVo.class);
                resultVo.setUploadedFile(uploadedFile);
                resultVo.setOssList(ossList);
                return resultVo;
            } else {
                throw new AppException("未能成功提交");
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw new AppException(ex.getMessage());
        }
    }

    /**
     * 删除行驶证主页
     *
     * @param ossId
     * @param ossUrl
     * @return
     */
    @Override
    public BaseInstallOrderProcessVo removeVehicleLicenseMainPage(String processId, String ossId, String ossUrl) {
        log.info("[删除行驶证主页][开始]");
        log.info("[删除行驶证主页][入参][{}][{}]", ossId, ossUrl);
        BaseInstallOrderProcessVo process = installOrderProcessService.queryById(processId);
        if (process != null) {

            List<String> ossIds = (StrUtil.isEmpty(process.getOssId())) ? new ArrayList<>() : Arrays.stream(process.getOssId().split(",")).collect(Collectors.toList());
            if (ossIds.contains(ossId)) {
                ossIds.remove(ossId);
            }

            List<String> ossUrls = (StrUtil.isEmpty(process.getOssUrl())) ? new ArrayList<>() : Arrays.stream(process.getOssUrl().split(",")).collect(Collectors.toList());
            if (ossUrls.contains(ossUrl)) {
                ossUrls.remove(ossUrl);
            }


            if (ossIds.size() == 0) {
                process.setOssId("");
                process.setOssUrl("");
            } else {
                process.setOssId(ossIds.size() == 1 ? ossIds.get(0) : ossIds.stream().collect(Collectors.joining(",")));
            }
            List<RemoteFile> ossList = remoteFileService.selectByIds(process.getOssId());
            if (ossIds.size() == 0) {
                process.setOssUrl("");
            } else {
//                process.setOssUrl(ossUrls.size() == 1 ? ossUrls.get(0) : ossUrls.stream().collect(Collectors.joining(",")));
                process.setOssUrl(ossList.stream().map(x -> x.getUrl().toString()).collect(Collectors.joining(",")));
            }

            if (installOrderProcessService.updateByBo(BeanCopyUtils.copy(process, BaseInstallOrderProcessBo.class))) {
//                for (String fileId : ossIds) {
//                    RemoteFile ossFile = remoteFileService.getFile(fileId);
//                    ossList.add(ossFile);
//                }
                process.setOssList(ossList);

                return process;
            } else {
                throw new AppException("删除失败");
            }
        } else {
            throw new AppException("未找到该步骤信息");
        }
    }

    /**
     * 上传行驶证副页
     *
     * @param files           行驶证副页图片列表
     * @param installActionBo 上传行驶证副页参数
     * @return
     */
    @Override
    public BaseInstallOrderProcessVo uploadVehicleLcenseSubPage(List<MultipartFile> files, DoInstallActionBo installActionBo) {
        try {
            List<RemoteFile> sysFiles = new ArrayList<>();
            for (MultipartFile file : files) {
                RemoteFile uploadedFile = remoteFileService.upload(file.getName(), file.getOriginalFilename(), "image", file.getBytes());
                sysFiles.add(uploadedFile);
            }
            BaseInstallOrderProcessBo installOrderProcessBo = new BaseInstallOrderProcessBo();
            installOrderProcessBo.setInstallOrderId(installActionBo.getOrderId());
            String ossIds = sysFiles.stream().map(x -> x.getOssId().toString()).collect(Collectors.joining(","));
            installOrderProcessBo.setOssId(ossIds);
            String ossUrls = sysFiles.stream().map(x -> x.getUrl().toString()).collect(Collectors.joining(","));
            installOrderProcessBo.setOssUrl(ossUrls);
            installOrderProcessBo.setStepId(installActionBo.getStepId());
            installOrderProcessBo.setStepGroupName(installActionBo.getStepGroupId());
            if (installOrderProcessService.insertByBo(installOrderProcessBo)) {
                return BeanCopyUtils.copy(installOrderProcessBo, BaseInstallOrderProcessVo.class);
            } else {
                throw new AppException("未能成功提交");
            }

        } catch (Exception ex) {
            throw new AppException(ex.getMessage());
        }
    }

    /**
     * 上传行驶证副页
     *
     * @param files           行驶证副页图片列表
     * @param installActionBo 上传行驶证副页参数
     * @return
     */
    @Override
    public BaseInstallOrderProcessUploadVo addVehicleLcenseSubPage(MultipartFile file, DoInstallActionBo installActionBo) {
        log.info("[添加驾驶证副业][开始]");
        log.info("[添加驾驶证副业][入参][{}][{}]", file.getOriginalFilename(), JSON.toJSONString(installActionBo));
        try {
            // 定义返回值
            BaseInstallOrderProcessUploadVo resultVo = null;

            // 检查是否已经有了数据
            BaseInstallOrderProcessBo process = null;
            Boolean isNew = false;

            BaseInstallOrderProcessBo query = new BaseInstallOrderProcessBo();
            query.setStepId(installActionBo.getStepId());
            query.setInstallOrderId(installActionBo.getOrderId());
            List<BaseInstallOrderProcessVo> vos = installOrderProcessService.queryList(query);

            if (CollUtil.isEmpty(vos)) {
                isNew = true;
                process = new BaseInstallOrderProcessBo();
                process.setInstallOrderId(installActionBo.getOrderId());
                process.setStepId(installActionBo.getStepId());
                process.setStepGroupName(installActionBo.getStepGroupId());
            } else {
                process = BeanCopyUtils.copy(vos.get(0), BaseInstallOrderProcessBo.class);
            }

            List<String> ossIds = (isNew || StrUtil.isEmpty(process.getOssId())) ? new ArrayList<>() : Arrays.stream(process.getOssId().split(",")).collect(Collectors.toList());
            List<String> ossUrls = (isNew || StrUtil.isEmpty(process.getOssUrl())) ? new ArrayList<>() : Arrays.stream(process.getOssUrl().split(",")).collect(Collectors.toList());

            if (ossIds.size() >= 3) {
                throw new AppException("附件已经到达最大值");
            }

            // 上传文件
            RemoteFile uploadedFile = remoteFileService.upload(file.getName(), file.getOriginalFilename(), "image", file.getBytes());

            if (!ossIds.contains(uploadedFile.getOssId())) {
                ossIds.add(uploadedFile.getOssId().toString());
            }
            if (!ossUrls.contains(uploadedFile.getUrl())) {
                ossUrls.add(uploadedFile.getUrl());
            }

            process.setOssId(ossIds.size() == 1 ? ossIds.get(0) : ossIds.stream().collect(Collectors.joining(",")));
//            process.setOssUrl(ossUrls.size() == 1 ? ossUrls.get(0) : ossUrls.stream().collect(Collectors.joining(",")));
            List<RemoteFile> ossList = remoteFileService.selectByIds(process.getOssId());
            process.setOssUrl(ossList.stream().map(x -> x.getUrl().toString()).collect(Collectors.joining(",")));

            if ((isNew && installOrderProcessService.insertByBo(process)) || (!isNew && installOrderProcessService.updateByBo(process))) {
                resultVo = BeanCopyUtils.copy(process, BaseInstallOrderProcessUploadVo.class);
                resultVo.setUploadedFile(uploadedFile);
                resultVo.setOssList(ossList);
                return resultVo;
            } else {
                throw new AppException("未能成功提交");
            }

        } catch (Exception ex) {
            throw new AppException(ex.getMessage());
        }
    }

    /**
     * 删除行驶证副页
     *
     * @param ossId
     * @param ossUrl
     * @return
     */
    @Override
    public BaseInstallOrderProcessVo removeVehicleLcenseSubPage(String processId, String ossId, String ossUrl) {
        log.info("[删除行驶证副页][开始]");
        log.info("[删除行驶证副页][入参][{}][{}]", ossId, ossUrl);
        BaseInstallOrderProcessVo process = installOrderProcessService.queryById(processId);
        if (process != null) {

            List<String> ossIds = (StrUtil.isEmpty(process.getOssId())) ? new ArrayList<>() : Arrays.stream(process.getOssId().split(",")).collect(Collectors.toList());
            if (ossIds.contains(ossId)) {
                ossIds.remove(ossId);
            }

            List<String> ossUrls = (StrUtil.isEmpty(process.getOssUrl())) ? new ArrayList<>() : Arrays.stream(process.getOssUrl().split(",")).collect(Collectors.toList());
            if (ossUrls.contains(ossUrl)) {
                ossUrls.remove(ossUrl);
            }

            if (ossIds.size() == 0) {
                process.setOssId("");
                process.setOssUrl("");
            } else {
                process.setOssId(ossIds.size() == 1 ? ossIds.get(0) : ossIds.stream().collect(Collectors.joining(",")));
            }
            List<RemoteFile> ossList = remoteFileService.selectByIds(process.getOssId());
            if (ossIds.size() == 0) {
                process.setOssUrl("");
            } else {
//                process.setOssUrl(ossUrls.size() == 1 ? ossUrls.get(0) : ossUrls.stream().collect(Collectors.joining(",")));
                process.setOssUrl(ossList.stream().map(x -> x.getUrl().toString()).collect(Collectors.joining(",")));
            }

            if (installOrderProcessService.updateByBo(BeanCopyUtils.copy(process, BaseInstallOrderProcessBo.class))) {

                process.setOssList(ossList);

                return process;
            } else {
                throw new AppException("删除失败");
            }
        } else {
            throw new AppException("未找到该步骤信息");
        }
    }

    /**
     * 上传车身照片
     *
     * @param file            车身照片
     * @param installActionBo 上传车身照参数
     * @return
     */
    @Override
    public BaseInstallOrderProcessUploadVo uploadCarPhotoForCarNo(MultipartFile file, DoInstallActionBo installActionBo) {
        try {
            // 定义返回值
            BaseInstallOrderProcessUploadVo resultVo = null;

            // 检查是否已经有了数据
            BaseInstallOrderProcessBo process = null;
            Boolean isNew = false;

            BaseInstallOrderProcessBo query = new BaseInstallOrderProcessBo();
            query.setStepId(installActionBo.getStepId());
            query.setInstallOrderId(installActionBo.getOrderId());
            List<BaseInstallOrderProcessVo> vos = installOrderProcessService.queryList(query);

            if (CollUtil.isEmpty(vos)) {
                isNew = true;
                process = new BaseInstallOrderProcessBo();
                process.setInstallOrderId(installActionBo.getOrderId());
                process.setStepId(installActionBo.getStepId());
                process.setStepGroupName(installActionBo.getStepGroupId());
            } else {
                process = BeanCopyUtils.copy(vos.get(0), BaseInstallOrderProcessBo.class);
            }

            RemoteFile uploadedFile = remoteFileService.upload(file.getName(), file.getOriginalFilename(), "image", file.getBytes());
            process.setOssId(uploadedFile.getOssId().toString());
            process.setOssUrl(uploadedFile.getUrl());

            if ((isNew && installOrderProcessService.insertByBo(process)) || (!isNew && installOrderProcessService.updateByBo(process))) {
                resultVo = BeanCopyUtils.copy(process, BaseInstallOrderProcessUploadVo.class);
                resultVo.setUploadedFile(uploadedFile);
                return resultVo;
            } else {
                throw new AppException("未能成功提交");
            }

        } catch (Exception ex) {
            throw new AppException(ex.getMessage());
        }
    }

    /**
     * 上传安装前接线处照片
     *
     * @param file            安装前接线处照片
     * @param installActionBo 上传安装前接线处照片参数
     * @return
     */
    @Override
    public BaseInstallOrderProcessUploadVo uploadBeforeInstallConnectionPointPhoto(MultipartFile file, DoInstallActionBo installActionBo) {
        try {
            // 定义返回值
            BaseInstallOrderProcessUploadVo resultVo = null;

            // 检查是否已经有了数据
            BaseInstallOrderProcessBo process = null;
            Boolean isNew = false;

            BaseInstallOrderProcessBo query = new BaseInstallOrderProcessBo();
            query.setStepId(installActionBo.getStepId());
            query.setInstallOrderId(installActionBo.getOrderId());
            List<BaseInstallOrderProcessVo> vos = installOrderProcessService.queryList(query);

            if (CollUtil.isEmpty(vos)) {
                isNew = true;
                process = new BaseInstallOrderProcessBo();
                process.setInstallOrderId(installActionBo.getOrderId());
                process.setStepId(installActionBo.getStepId());
                process.setStepGroupName(installActionBo.getStepGroupId());
            } else {
                process = BeanCopyUtils.copy(vos.get(0), BaseInstallOrderProcessBo.class);
            }

            RemoteFile uploadedFile = remoteFileService.upload(file.getName(), file.getOriginalFilename(), "image", file.getBytes());
            process.setOssId(uploadedFile.getOssId().toString());
            process.setOssUrl(uploadedFile.getUrl());

            if ((isNew && installOrderProcessService.insertByBo(process)) || (!isNew && installOrderProcessService.updateByBo(process))) {
                resultVo = BeanCopyUtils.copy(process, BaseInstallOrderProcessUploadVo.class);
                resultVo.setUploadedFile(uploadedFile);
                return resultVo;
            } else {
                throw new AppException("未能成功提交");
            }

        } catch (Exception ex) {
            throw new AppException(ex.getMessage());
        }
    }

    /**
     * 上传安装后接线处照片
     *
     * @param file            安装后接线处照片
     * @param installActionBo 上传安装后接线处照片参数
     * @return
     */
    @Override
    public BaseInstallOrderProcessUploadVo uploadAfterInstallConnectionPointPhoto(MultipartFile file, DoInstallActionBo installActionBo) {
        try {
            // 定义返回值
            BaseInstallOrderProcessUploadVo resultVo = null;

            // 检查是否已经有了数据
            BaseInstallOrderProcessBo process = null;
            Boolean isNew = false;

            BaseInstallOrderProcessBo query = new BaseInstallOrderProcessBo();
            query.setStepId(installActionBo.getStepId());
            query.setInstallOrderId(installActionBo.getOrderId());
            List<BaseInstallOrderProcessVo> vos = installOrderProcessService.queryList(query);

            if (CollUtil.isEmpty(vos)) {
                isNew = true;
                process = new BaseInstallOrderProcessBo();
                process.setInstallOrderId(installActionBo.getOrderId());
                process.setStepId(installActionBo.getStepId());
                process.setStepGroupName(installActionBo.getStepGroupId());
            } else {
                process = BeanCopyUtils.copy(vos.get(0), BaseInstallOrderProcessBo.class);
            }

            RemoteFile uploadedFile = remoteFileService.upload(file.getName(), file.getOriginalFilename(), "image", file.getBytes());
            process.setOssId(uploadedFile.getOssId().toString());
            process.setOssUrl(uploadedFile.getUrl());

            if ((isNew && installOrderProcessService.insertByBo(process)) || (!isNew && installOrderProcessService.updateByBo(process))) {
                resultVo = BeanCopyUtils.copy(process, BaseInstallOrderProcessUploadVo.class);
                resultVo.setUploadedFile(uploadedFile);
                return resultVo;
            } else {
                throw new AppException("未能成功提交");
            }

        } catch (Exception ex) {
            throw new AppException(ex.getMessage());
        }
    }

    /**
     * 上传安装位置照片
     *
     * @param file            安装位置照片
     * @param installActionBo 上传安装位置照片参数
     * @return
     */
    @Override
    public BaseInstallOrderProcessUploadVo uploadInstallPostionPhoto(MultipartFile file, DoInstallActionBo installActionBo) {
        try {
            // 定义返回值
            BaseInstallOrderProcessUploadVo resultVo = null;

            // 检查是否已经有了数据
            BaseInstallOrderProcessBo process = null;
            Boolean isNew = false;

            BaseInstallOrderProcessBo query = new BaseInstallOrderProcessBo();
            query.setStepId(installActionBo.getStepId());
            query.setInstallOrderId(installActionBo.getOrderId());
            List<BaseInstallOrderProcessVo> vos = installOrderProcessService.queryList(query);

            if (CollUtil.isEmpty(vos)) {
                isNew = true;
                process = new BaseInstallOrderProcessBo();
                process.setInstallOrderId(installActionBo.getOrderId());
                process.setStepId(installActionBo.getStepId());
                process.setStepGroupName(installActionBo.getStepGroupId());
            } else {
                process = BeanCopyUtils.copy(vos.get(0), BaseInstallOrderProcessBo.class);
            }

            RemoteFile uploadedFile = remoteFileService.upload(file.getName(), file.getOriginalFilename(), "image", file.getBytes());
            process.setOssId(uploadedFile.getOssId().toString());
            process.setOssUrl(uploadedFile.getUrl());

            if ((isNew && installOrderProcessService.insertByBo(process)) || (!isNew && installOrderProcessService.updateByBo(process))) {
                resultVo = BeanCopyUtils.copy(process, BaseInstallOrderProcessUploadVo.class);
                resultVo.setUploadedFile(uploadedFile);
                return resultVo;
            } else {
                throw new AppException("未能成功提交");
            }

        } catch (Exception ex) {
            throw new AppException(ex.getMessage());
        }
    }

    /**
     * 上传里程表照片
     *
     * @param file            里程表照片
     * @param installActionBo 上传里程表照片参数
     * @return
     */
    @Override
    public BaseInstallOrderProcessUploadVo uploadOdometerPhoto(MultipartFile file, DoInstallActionBo installActionBo) {
        try {
            // 定义返回值
            BaseInstallOrderProcessUploadVo resultVo = null;

            // 检查是否已经有了数据
            BaseInstallOrderProcessBo process = null;
            Boolean isNew = false;

            BaseInstallOrderProcessBo query = new BaseInstallOrderProcessBo();
            query.setStepId(installActionBo.getStepId());
            query.setInstallOrderId(installActionBo.getOrderId());
            List<BaseInstallOrderProcessVo> vos = installOrderProcessService.queryList(query);

            if (CollUtil.isEmpty(vos)) {
                isNew = true;
                process = new BaseInstallOrderProcessBo();
                process.setInstallOrderId(installActionBo.getOrderId());
                process.setStepId(installActionBo.getStepId());
                process.setStepGroupName(installActionBo.getStepGroupId());
            } else {
                process = BeanCopyUtils.copy(vos.get(0), BaseInstallOrderProcessBo.class);
            }

            RemoteFile uploadedFile = remoteFileService.upload(file.getName(), file.getOriginalFilename(), "image", file.getBytes());
            process.setOssId(uploadedFile.getOssId().toString());
            process.setOssUrl(uploadedFile.getUrl());

            if ((isNew && installOrderProcessService.insertByBo(process)) || (!isNew && installOrderProcessService.updateByBo(process))) {
                resultVo = BeanCopyUtils.copy(process, BaseInstallOrderProcessUploadVo.class);
                resultVo.setUploadedFile(uploadedFile);
                return resultVo;
            } else {
                throw new AppException("未能成功提交");
            }

        } catch (Exception ex) {
            throw new AppException(ex.getMessage());
        }
    }

    /**
     * 检查设备安装信息
     *
     * @param installActionBo 设备激活参数
     * @return
     */
    @Override
    public InstallCheckResultVo checkDeviceInstallInfo(DoInstallActionBo installActionBo) {

        String imei = installOrderProcessService.getOrderImei(installActionBo.getOrderId());
        if (StrUtil.isBlank(imei)) {
            log.error("订单 {} 没有绑定 IMEI", installActionBo.getOrderId());
            throw new AppException("未绑定IMEI");
        }

        log.info("检测设备 {} 安装情况开始", imei);

        GisTimePosistionVo gisTimePosistionVo = null;
        try {
            gisTimePosistionVo = remoteThirdDistributeService.checkTerminalInfo(installActionBo.getOrderId(), imei);
        } catch (Exception ex) {

            log.error("检测设备 {} 安装情况时发生异常: ", imei, ex);

            if (!remoteThirdDistributeService.registerTerminal(installActionBo.getOrderId(), imei)) {
                throw new AppException("终端注册失败");
            }

            gisTimePosistionVo = remoteThirdDistributeService.checkTerminalInfo(installActionBo.getOrderId(), imei);
        }

        InstallCheckResultVo vo = new InstallCheckResultVo();
        vo.setCheckResult(1);
        vo.setCheckPosition(gisTimePosistionVo);
//        Random random = new Random();
//        Integer ir = random.nextInt(100) % 3;
//        if (ir == 1) {
//            GisTimePosistionVo gisTimePosistionVo = new GisTimePosistionVo();
//            gisTimePosistionVo.setSendTime(LocalDateTime.now());
//            gisTimePosistionVo.setLongitude(new BigDecimal(120.0));
//            gisTimePosistionVo.setLatitude(new BigDecimal(36.0));
//            vo.setCheckPosition(gisTimePosistionVo);
//        }
//        vo.setCheckResult(ir);
        return vo;
    }

    /**
     * 检查设备激活信息
     *
     * @param installActionBo 设备激活参数
     * @return
     */
    @Override
    public InstallActiveResultVo checkDeviceActiveInfo(DoInstallActionBo installActionBo) {

        String imei = installOrderProcessService.getOrderImei(installActionBo.getOrderId());
        if (StrUtil.isBlank(imei)) {
            throw new AppException("未绑定IMEI");
        }

        log.info("激活设备 {} 开始", imei);

        GisTimePosistionVo gisTimePosistionVo = null;
        try {
            gisTimePosistionVo = remoteThirdDistributeService.checkTerminalInfo(installActionBo.getOrderId(), imei);
        } catch (Exception ex) {

            log.error("激活设备 {} 时发生异常: ", imei, ex);

            if (!remoteThirdDistributeService.registerTerminal(installActionBo.getOrderId(), imei)) {
                throw new AppException("终端注册失败");
            }

            gisTimePosistionVo = remoteThirdDistributeService.checkTerminalInfo(installActionBo.getOrderId(), imei);
        }

        log.info("激活设备 {} 结束", imei);

        InstallActiveResultVo vo = new InstallActiveResultVo();
        vo.setCheckResult(1);
        List<GisTimePosistionVo> gisTimePosistionVoList = new ArrayList<>();
        gisTimePosistionVoList.add(gisTimePosistionVo);
        vo.setCheckPositionList(gisTimePosistionVoList);


//        Random random = new Random();
//        Integer ir = random.nextInt(100) % 3;
//        if (ir == 1) {
//            List<GisTimePosistionVo> gisTimePosistionVoList = new ArrayList<>();
//            for (int i = 0; i < 100; i++) {
//                GisTimePosistionVo gisTimePosistionVo = new GisTimePosistionVo();
//                gisTimePosistionVo.setSendTime(LocalDateTime.now().plusSeconds(4 * i));
//                gisTimePosistionVo.setLongitude(new BigDecimal(120.0 + i * 0.004));
//                gisTimePosistionVo.setLatitude(new BigDecimal(36.0 + i * 0.002));
//                gisTimePosistionVoList.add(gisTimePosistionVo);
//            }
//            vo.setCheckPositionList(gisTimePosistionVoList);
//        }
//        vo.setCheckResult(ir);
        return vo;
    }

    /**
     * 创建安装单
     *
     * @return 安装单
     */
    @Override
    public BaseInstallOrder createInstallOrder(BaseSaleOrder saleOrder) {

        // 获取安装码
        String installCode = orderHelper.getInstallCode();

        // 创建安装单
        BaseInstallOrder installOrder = new BaseInstallOrder();
        installOrder.setInstallCode(installCode);

        String fullJumpUrl = SecureUtil.md5(installCode).toUpperCase().substring(0, 8);
        installOrder.setId(orderHelper.getInstallOrderId());
        installOrder.setInstallUrl(baseDomain + fullJumpUrl);
        installOrder.setCarNo(saleOrder.getCarNo());
        installOrder.setSaleOrderId(saleOrder.getId());
        installOrder.setStatus(InstallOrderStatus.WAITING.getValue());

        baseInstallOrderMapper.insert(installOrder);

        return installOrder;
    }

    @Override
    public BaseInstallOrderVo getInstallingOrder(String userId) {
        List<BaseInstallOrder> installOrderList = baseInstallOrderMapper.selectList(
            new LambdaQueryWrapper<BaseInstallOrder>()
                .eq(BaseInstallOrder::getStatus, InstallOrderStatus.ACCEPTED.getValue())
                .eq(BaseInstallOrder::getInstallManId, userId)
        );

        if (CollUtil.isEmpty(installOrderList)) {
            return null;
        }

        BaseInstallOrderVo installOrderVo = BeanCopyUtils.copy(CollUtil.getFirst(installOrderList), BaseInstallOrderVo.class);

        // 填充信息
        return installOrderVo;
    }

    @Override
    public List<BaseInstallOrderVo> getInstallOrderByCarNo(String cardNo) {

        List<BaseInstallOrderVo> installOrderList = baseInstallOrderMapper.selectVoList(
            new LambdaQueryWrapper<BaseInstallOrder>()
                .eq(BaseInstallOrder::getCarNo, cardNo)
                .eq(BaseInstallOrder::getStatus, InstallOrderStatus.WAITING.getValue())
        );

        if (CollUtil.isEmpty(installOrderList)) {
            return null;
        }

        for (BaseInstallOrderVo installOrderVo : installOrderList) {
//            BaseInstallOrderVo installOrderVo = BeanCopyUtils.copy(CollUtil.getFirst(installOrderList), BaseInstallOrderVo.class);
            installOrderVo.setStartType("车牌号");
            baseInstallOrderMapper.updateById(BeanCopyUtils.copy(installOrderVo, BaseInstallOrder.class));

            // 填充信息
            BaseSaleOrderVo baseSaleOrderVo = baseSaleOrderService.queryById(installOrderVo.getSaleOrderId());
            if (baseSaleOrderVo != null) {
                BaseProductVo baseProductVo = baseProductService.queryById(baseSaleOrderVo.getProductId());
                String productPosterUrl = remoteFileService.selectUrlByIds(baseProductVo.getProductPoster());
                baseProductVo.setProductPosterUrl(productPosterUrl);
                String productThumbnailUrl = remoteFileService.selectUrlByIds(baseProductVo.getProductThumbnail());
                baseProductVo.setProductThumbnailUrl(productThumbnailUrl);
                baseSaleOrderVo.setProductThumbnailUrl(productThumbnailUrl);

                BaseDeviceVo baseDeviceVo = baseDeviceService.queryById(baseProductVo.getDeviceId());
                String devicePosterUrl = remoteFileService.selectUrlByIds(baseDeviceVo.getDevicePoster());
                baseDeviceVo.setDevicePosterUrl(devicePosterUrl);
                String deviceThumbnailUrl = remoteFileService.selectUrlByIds(baseDeviceVo.getDeviceThumbnail());
                baseDeviceVo.setDeviceThumbnailUrl(deviceThumbnailUrl);
                baseProductVo.setDeviceInfo(baseDeviceVo);

                baseSaleOrderVo.setProductInfo(baseProductVo);
            }
            installOrderVo.setSaleOrderVo(baseSaleOrderVo);
        }

        return installOrderList;
    }

    @Override
    public List<BaseInstallOrderVo>  getInstallOrderByInstallCode(String installCode) {

        List<BaseInstallOrderVo> installOrderList = baseInstallOrderMapper.selectVoList(
            new LambdaQueryWrapper<BaseInstallOrder>()
                .eq(BaseInstallOrder::getInstallCode, installCode)
                .eq(BaseInstallOrder::getStatus, InstallOrderStatus.WAITING.getValue())
        );

        if (CollUtil.isEmpty(installOrderList)) {
            return null;
        }

        for (BaseInstallOrderVo installOrderVo : installOrderList) {
//            BaseInstallOrderVo installOrderVo = BeanCopyUtils.copy(CollUtil.getFirst(installOrderList), BaseInstallOrderVo.class);
            installOrderVo.setStartType("安装码");
            baseInstallOrderMapper.updateById(BeanCopyUtils.copy(installOrderVo, BaseInstallOrder.class));

            // 填充信息
            BaseSaleOrderVo baseSaleOrderVo = baseSaleOrderService.queryById(installOrderVo.getSaleOrderId());
            if (baseSaleOrderVo != null) {
                BaseProductVo baseProductVo = baseProductService.queryById(baseSaleOrderVo.getProductId());
                String productPosterUrl = remoteFileService.selectUrlByIds(baseProductVo.getProductPoster());
                baseProductVo.setProductPosterUrl(productPosterUrl);
                String productThumbnailUrl = remoteFileService.selectUrlByIds(baseProductVo.getProductThumbnail());
                baseProductVo.setProductThumbnailUrl(productThumbnailUrl);
                baseSaleOrderVo.setProductThumbnailUrl(productThumbnailUrl);

                BaseDeviceVo baseDeviceVo = baseDeviceService.queryById(baseProductVo.getDeviceId());
                String devicePosterUrl = remoteFileService.selectUrlByIds(baseDeviceVo.getDevicePoster());
                baseDeviceVo.setDevicePosterUrl(devicePosterUrl);
                String deviceThumbnailUrl = remoteFileService.selectUrlByIds(baseDeviceVo.getDeviceThumbnail());
                baseDeviceVo.setDeviceThumbnailUrl(deviceThumbnailUrl);
                baseProductVo.setDeviceInfo(baseDeviceVo);

                baseSaleOrderVo.setProductInfo(baseProductVo);
            }
            installOrderVo.setSaleOrderVo(baseSaleOrderVo);
        }

        return installOrderList;
    }

    /**
     * 分页查询安装订单
     * @param queryBo
     * @return
     */
    @Override
    public TableDataInfo getInstallOrderPageList(InstallOrderQueryBo queryBo) {
        log.info("[开始安装][开始]");
        log.info("[开始安装][入参][安装订单号： {} , 安装人员： {}]", queryBo);

        QueryWrapper qw = buildQueryWrapper(queryBo);

        Page<BaseInstallOrderVo> installOrderVoPage = appInstallMapper.searchPageList(queryBo.build(), qw);

        return TableDataInfo.build(installOrderVoPage);
    }

    /**
     * 开始安装
     * @param installOrderId
     * @param userId
     * @return
     */
    @Override
    public BaseInstallOrderVo startInstall(String installOrderId, String userId) {
        log.info("[开始安装][开始]");
        log.info("[开始安装][入参][安装订单号： {} , 安装人员： {}]", installOrderId, userId);
        BaseInstallOrder installOrder = baseInstallOrderMapper.selectById(installOrderId);
        if (installOrder == null) {
            return null;
        }
        if (installOrder.getStatus() != InstallOrderStatus.WAITING.getValue()) {
            throw new UserException("安装单已被接单");
        }

        installOrder.setInstallManId(userId);
        installOrder.setStatus(InstallOrderStatus.ACCEPTED.getValue());
        installOrder.setStartTime(LocalDateTime.now());

        if (baseInstallOrderMapper.updateById(installOrder) == 1) {
            return BeanCopyUtils.copy(installOrder, BaseInstallOrderVo.class);
        } else {
            return null;
        }
    }

    /**
     * 安装提交
     * @param installOrderId 安装订单号
     * @param userId 安装人员标识
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public BaseInstallOrderVo submitInstall(String installOrderId, String userId) {
        log.info("[安装提交][开始]");
        log.info("[安装提交][入参][安装订单号： {} , 安装人员： {}]", installOrderId, userId);
        BaseInstallOrder installOrder = baseInstallOrderMapper.selectById(installOrderId);
        if (installOrder == null) {
            return null;
        }
        if (installOrder.getStatus() != InstallOrderStatus.ACCEPTED.getValue() || !installOrder.getInstallManId().equals(userId)) {
            throw new AppException("用户无法提交该安装单");
        }

        installOrder.setStatus(InstallOrderStatus.INSTALLED.getValue());
        installOrder.setInstallStatus(1);
        installOrder.setSubmitTime(LocalDateTime.now());

        if (!remoteThirdDistributeService.takeUpTerminal(installOrderId, installOrder.getImei())) {
            throw new AppException("设备占用失败");
        }

        if (baseSaleOrderMapper.update(
            new LambdaUpdateWrapper<BaseSaleOrder>().eq(BaseSaleOrder::getInstallOrderId, installOrderId).set(BaseSaleOrder::getStatus, SaleOrderStatus.INSTALLED.getValue())
        ) <= 0) {
            throw new AppException("更新销售订单失败");
        }

        if (baseInstallOrderMapper.updateById(installOrder) == 1) {
            return BeanCopyUtils.copy(installOrder, BaseInstallOrderVo.class);
        } else {
            throw new AppException("更新安装订单失败");
        }
    }

    /**
     * 百度OCR识别(驾驶证）
     * @param file
     * @return
     */
    @Override
    public String baiduCarNoOcr(MultipartFile file) {
        log.info("[百度OCR识别(驾驶证）][开始]");
        log.info("[百度OCR识别(驾驶证）][入参][{}]", file.getOriginalFilename());
        try {
            // 传入可选参数调用接口
            HashMap<String, String> options = new HashMap<String, String>();
            options.put("multi_detect", "false");

            byte[] image = file.getBytes();
            JSONObject jsonObject = baiduAipClient.createAipOcr().plateLicense(image, options);
            if (jsonObject != null) {
                if (jsonObject.has("words_result")) {
                    JSONObject wordsResult = jsonObject.getJSONObject("words_result");
                    if (wordsResult.has("number")) {
                        return wordsResult.getString("number");
                    }
                }
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取安装进度详情
     * @param orderId
     * @return
     */
    @Override
    public List<BaseInstallOrderProcessVo> getInstallOrderProcessList(String orderId) {
        log.info("[获取安装进度详情][开始]");
        log.info("[获取安装进度详情][入参][{}]", orderId);
        BaseInstallOrderProcessBo baseInstallOrderProcess = new BaseInstallOrderProcessBo();
        baseInstallOrderProcess.setInstallOrderId(orderId);

        List<BaseInstallOrderProcessVo> resutlList = installOrderProcessService.queryList(baseInstallOrderProcess);
        for (BaseInstallOrderProcessVo vo : resutlList) {
            if (StrUtil.isNotEmpty(vo.getOssId())) {
                List<RemoteFile> ossList = remoteFileService.selectByIds(vo.getOssId());
                vo.setOssList(ossList);
            }
        }
        return resutlList;
    }

    /**
     * 获取公开信息
     *
     * @param jumpUrl 跳转地址
     * @return
     */
    @Override
    public InstallOrderPublicDetailVo getInstallOrderPublicDetail(String jumpUrl) {
        log.info("[获取公开信息][开始]");
        log.info("[获取公开信息][入参][{}]", jumpUrl);
        BaseInstallOrder installOrder = baseInstallOrderMapper.selectOne(
            new LambdaQueryWrapper<BaseInstallOrder>()
                .eq(BaseInstallOrder::getInstallUrl, baseDomain + jumpUrl)
        );

        BaseSaleOrder saleOrder = baseSaleOrderMapper.selectById(installOrder.getSaleOrderId());

        BaseUser baseUser = baseUserMapper.selectById(saleOrder.getSalesManId());

        if (saleOrder == null) {
            throw new AppException("10021", "未查询到销售订单");
        }

        InstallOrderPublicDetailVo installOrderPublicDetailVo = new InstallOrderPublicDetailVo();
        installOrderPublicDetailVo.setOrderId(saleOrder.getId());

        String customerName = saleOrder.getLastName();
        String callerName = Gender.of(saleOrder.getGender()).getLabel();
        installOrderPublicDetailVo.setCustomerName(customerName + callerName);

        installOrderPublicDetailVo.setCustomerPhone(saleOrder.getPhone());
        installOrderPublicDetailVo.setCustomerCarNo(saleOrder.getCarNo());

        BaseProduct baseProduct = baseProductMapper.selectById(saleOrder.getProductId());
        String productPosterUrl = remoteFileService.selectUrlByIds(baseProduct.getProductPoster());
        String productThumbnailUrl = remoteFileService.selectUrlByIds(baseProduct.getProductThumbnail());

        installOrderPublicDetailVo.setProductName(baseProduct.getProductName());
        installOrderPublicDetailVo.setProductId(baseProduct.getId());

        BaseDevice baseDevice = baseDeviceMapper.selectById(baseProduct.getDeviceId());
        String devicePosterUrl = remoteFileService.selectUrlByIds(baseDevice.getDevicePoster());
        String deviceThumbnailUrl = remoteFileService.selectUrlByIds(baseDevice.getDeviceThumbnail());
        installOrderPublicDetailVo.setDeviceId(baseDevice.getId());
        installOrderPublicDetailVo.setDeviceName(baseDevice.getDeviceName());

        BaseCompany baseCompany = baseCompanyMapper.selectById(baseUser.getCompanyId());
//        BaseSaleChannel baseSaleChannel = baseSaleChannelMapper.selectOne(
//            new LambdaQueryWrapper<BaseSaleChannel>()
//                .eq(BaseSaleChannel::getChannelCode, baseCompany.getChannelCode())
//        );

        if (installOrder != null) {
            installOrderPublicDetailVo.setCustomerInstallCode(installOrder.getInstallCode());
        }

        return installOrderPublicDetailVo;
    }

    private QueryWrapper buildQueryWrapper(InstallOrderQueryBo queryBo) {
        QueryWrapper<BaseInstallOrder> qw = new QueryWrapper<>();
        String queryParam = queryBo.getQueryParam();
        AppLoginUser appLoginUser = AppLoginHelper.getAppLoginUser();
        qw.eq("installOrder.install_man_id", appLoginUser.getUserId());
        if (StringUtils.isNotEmpty(queryParam)) {
            qw.and(iqw ->
                iqw.like("saleOrder.last_name", queryParam)
                    .or()
                    .like("saleOrder.id", queryParam)
                    .or()
                    .like("saleOrder.phone", queryParam)
                    .or()
                    .like("product.product_name", queryParam)
                    .or()
                    .like("device.device_name", queryParam)
                    .or()
                    .like("device.device_model", queryParam)
                    .or()
                    .like("installOrder.install_code", queryParam)
            );
        }
        qw.eq(ObjectUtil.isNotEmpty(queryBo.getOrderStatus()), "installOrder.`status`", queryBo.getOrderStatus());

        return qw;
    }
}
